﻿using Furion;
using Furion.SpecificationDocument;
using IGeekFan.AspNetCore.Knife4jUI;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Synology;
using System;
using System.IO;

namespace apitest.Web.Core;

public class Startup : AppStartup
{


    public void ConfigureServices(IServiceCollection services)
    {


        services.AddConsoleFormatter();
        services.AddJwt<JwtHandler>();
        services.AddFileLogging("logs/application-{0:yyyy}-{0:MM}-{0:dd}.log", options =>
        {

            options.FileNameRule = fileName =>
            {
                return string.Format(fileName, DateTime.UtcNow);
            };
        });
        services.AddCorsAccessor();
        //services.AddCors(options =>  // 配置Cors跨域
        //{
        //    options.AddPolicy(name: "MyPolicy",
        //        policy =>
        //        {
        //            policy
        //            //.AllowAnyOrigin()
        //            .WithOrigins("http://172.16.205.175:9091", "http://172.16.205.175:9092")// 约束域名;.WithOrigins("")；一般不会允许所有域都可访问后台（AllowAnyOrigin()）
        //                .AllowAnyHeader() 
        //                .AllowCredentials()// 约束HTTP请求头-允许所有请求头；.WithHeaders("Content-Language","Content-Type");
        //                .AllowAnyMethod();                                                   // 约束HTTP方法-允许所有方法；.WithMethods("PUT", "DELETE", "GET","POST")

        //        });
        //});
        services.AddRemoteRequest();
        services.AddSqlsugarSetup();


        //services.AddViewEngine();

        services
          //  .AddHttpContextAccessor()
            .AddControllers()
                .AddInjectWithUnifyResult()
                .AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                }); ;

        services.AddIpRateLimitSetup();

        services.AddSynology(b =>
        {
            b.AddApi();
            b.AddAudioStation();
            b.AddDownloadStation();
            b.AddDownloadStation2();
            b.AddFileStation();
            b.AddSurveillanceStation();
            b.AddVideoStation();
        });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseIpLimit();
        var path = Path.Combine(env.ContentRootPath, "uploads");
        Console.WriteLine(path);
        if (!Directory.Exists(path))
        {
             
            Directory.CreateDirectory(path);
        }
        app.UseStaticFiles(new StaticFileOptions()
        {
            FileProvider = new PhysicalFileProvider(path),
            RequestPath = new PathString("/uploads")
        });

        app.UseRouting();
     
        //  app.UseCors("MyPolicy");  // 使用Cors跨域
        app.UseCorsAccessor();
        //app.UseIpRateLimiting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseKnife4UI(options =>
        {
            options.RoutePrefix = "";  // 配置 Knife4UI 路由地址，现在是 /newapi
            foreach (var groupInfo in SpecificationDocumentBuilder.GetOpenApiGroups())
            {
                options.SwaggerEndpoint("/" + groupInfo.RouteTemplate, groupInfo.Title);
            }
        });

       app.UseInject();


        //app.Use(async (context, next) =>
        //{
        //    // 比如设置统一头
        //    context.Response.Headers["framework"] = "Furion";
        //    System.Console.WriteLine(1111111111);
        //    // 执行下一个中间件
        //    await next.Invoke();
        //    //  await Task.FromResult(context);
        //});


        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
